package cn.tonyandmoney.voicenotes.wav.utils;

import android.util.Log;

import com.github.promeg.pinyinhelper.Pinyin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.tonyandmoney.voicenotes.notes.entity.TRecord;
import cn.tonyandmoney.voicenotes.utils.DateUtils;
import cn.tonyandmoney.voicenotes.wav.WavConstants;
import cn.tonyandmoney.voicenotes.wav.format.AudioEncoder;

public class CutUtils {
    private static final String TAG = "CutUtils";

    /**
     * @param record 原始文件
     * @param max    最大长度，分钟
     * @return 切割后的文件
     */
    public static List<TRecord> curPCM(TRecord record, int max) {
        List<TRecord> records = new ArrayList<>();
        /*每秒钟生成的文件大小单位为：byte*/
        int bitsPerSecond = record.getSampleRate() * record.getChannel() * record.getBitNum() / 8;
//        /**
//        * 确定长度下每个文件数据流的最大长度：byte
//         * 我并不太清楚这个地方为什么要乘以2才是最终正确的分割
//        * */
        int maxBitsPerFile = bitsPerSecond * max * 60 * 2;
        File src = new File(record.getPath());
        String name = Pinyin.toPinyin(record.getContent(), "");
        String parent = src.getParent() + "/" + name + "_" + DateUtils.INSTANCE.toYYYYMMDDHHmmss();
        File curFileParent = new File(parent);
        if (!curFileParent.exists()) curFileParent.mkdirs();
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;

        try {
            inputStream = new FileInputStream(src);
            byte[] temp = new byte[1024];
            int curFileLength = 0;
            int cutFileCount = 0;

            File cutFile = checkOutFile(curFileParent, name, cutFileCount);
            outputStream = new FileOutputStream(cutFile);

            int length = 0;
            while ((length = inputStream.read(temp)) != -1) {
                if (curFileLength >= maxBitsPerFile) {
                    outputStream.flush();
                    outputStream.close();
                    records.add(saveFile(cutFile, record, max * 60 * 1000));
                    curFileLength = 0;
                    cutFileCount++;
                    cutFile = checkOutFile(curFileParent, name, cutFileCount);
                    outputStream = new FileOutputStream(cutFile);
                }
                outputStream.write(temp, 0, length);
                curFileLength += length;
                Log.i(TAG, "length: " + length);
            }
            records.add(saveFile(cutFile, record, curFileLength * 500 / bitsPerSecond));
            src.delete();
        } catch (Exception e) {
            Log.e(TAG, "curPCM", e);
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return records;
    }


    private static File checkOutFile(File parent, String name, int count)
            throws IOException {
        File cutFile = new File(parent, name + "_" + count + ".pcm");
        cutFile.createNewFile();
        return cutFile;
    }

    private static TRecord saveFile(File file, TRecord record, long length) {
        String outPath = file.getAbsolutePath().replace("pcm", "wav");
        File outFile = new File(outPath);
        AudioEncoder.convertPcm2Wav(file, outFile, WavConstants.sampleRate, WavConstants.channels, WavConstants.bitNum);


        file.delete();
        TRecord newRecord = record.clone();
        newRecord.setPath(outPath);
        newRecord.setDuration(length);
        return newRecord;
    }

}
